<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="源代码" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          placeholder="请输入源代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="运行耗时" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="内存" prop="memory">
        <el-input
          v-model="queryParams.memory"
          placeholder="请输入内存使用量(KB)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="输出文件列表(逗号分隔)" prop="outfiles">
        <el-input
          v-model="queryParams.outfiles"
          placeholder="请输入输出文件列表(逗号分隔)"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['plus:submission:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['plus:submission:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="源代码" align="center" prop="sourceCode">
        <template #default="scope">
          <div class="code-preview">{{ decodeBase64(scope.row.sourceCode) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="运行耗时(s)" align="center" prop="time" />
      <el-table-column label="内存使用量(KB)" align="center" prop="memory" />
      <el-table-column label="输出文件列表" align="center" prop="outfiles" />
      <el-table-column label="关联文档" align="center" width="100">
        <template #default="scope">
          <el-button type="primary" link @click="goDocplus(scope.row.plusid)">关联文档</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('view', scope.row.id)"
            v-hasPermi="['plus:submission:update']"
          >
            查看详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['plus:submission:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <SubmissionForm ref="formRef" @success="getList" />
  
  <!-- Base64解码源代码详情弹窗 -->
  <el-dialog v-model="dialogVisible" title="源代码详情" width="70%" destroy-on-close>
    <div class="code-editor-container">
      <MonacoEditor
        v-model:value="selectedSourceCode"
        language="cpp"
        theme="vs"
        :options="{
          readOnly: true,
          minimap: { enabled: true },
          scrollBeyondLastLine: false,
          lineNumbers: 'on',
          automaticLayout: true,
          fontSize: 14
        }"
        style="height: 500px; width: 100%;"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { SubmissionApi, SubmissionVO } from '@/api/plus/submission'
import SubmissionForm from './SubmissionForm.vue'
import MonacoEditor from 'monaco-editor-vue3'
import { useRouter } from 'vue-router'

/** 代码提交 列表 */
defineOptions({ name: 'Submission' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SubmissionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined as number | undefined,
  sourceCode: undefined,
  time: [],
  memory: undefined,
  outfiles: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 源代码详情弹窗
const dialogVisible = ref(false)
const selectedSourceCode = ref('')

// 跳转到文档附加列表
const router = useRouter()
const goDocplus = (plusid: string) => {
  if (!plusid) return
  window.open(`/system/docplus?plusid=${plusid}`, '_blank')
}

/** Base64解码函数 */
const decodeBase64 = (encoded: string) => {
  if (!encoded) return ''
  try {
    // 使用更安全的方式解码Base64，并确保UTF-8编码正确处理
    const binary = atob(encoded)
    // 将二进制字符串转换为UTF-8字符串
    const bytes = new Uint8Array(binary.length)
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i)
    }
    // 使用TextDecoder将字节数组转换为UTF-8字符串
    const decoded = new TextDecoder('utf-8').decode(bytes)
    // 截取前30个字符并添加省略号，用于表格预览
    return decoded.length > 30 ? decoded.substring(0, 30) + '...' : decoded
  } catch (e) {
    console.error('Base64解码失败:', e)
    return '解码失败'
  }
}

/** 显示完整源代码 */
const showFullSourceCode = (code: string) => {
  if (!code) return
  try {
    // 使用相同的UTF-8解码逻辑
    const binary = atob(code)
    const bytes = new Uint8Array(binary.length)
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i)
    }
    selectedSourceCode.value = new TextDecoder('utf-8').decode(bytes)
    dialogVisible.value = true
  } catch (e) {
    console.error('Base64解码失败:', e)
    message.error('源代码解码失败')
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SubmissionApi.getSubmissionPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查看/添加操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (type === 'view') {
    // 查找对应的记录，获取源代码
    const item = list.value.find(item => item.id === id)
    if (item && item.sourceCode) {
      showFullSourceCode(item.sourceCode)
      return
    }
  }
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SubmissionApi.deleteSubmission(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SubmissionApi.exportSubmission(queryParams)
    download.excel(data, '代码提交.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.code-preview {
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 300px;
  font-family: monospace;
}

.source-code-detail {
  text-align: left;
  white-space: pre-wrap;
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  overflow: auto;
  max-height: 600px;
}

.code-editor-container {
  height: 500px;
  width: 100%;
}
</style>